package com.cykj.pos.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.utils.IschineseByutil;
import com.cykj.common.utils.StringUtils;
import com.cykj.pos.domain.dto.*;
import com.cykj.pos.enums.bizstatus.CommEnum;
import com.cykj.pos.mapper.*;
import com.cykj.pos.profit.dto.HomePageDataDTO;
import com.cykj.pos.profit.dto.MerchantDTO;
import com.cykj.pos.profit.dto.PartnerDetailDTO;
import com.cykj.pos.util.HttpUtil;
import com.cykj.pos.util.LoginUserUtils;
import com.google.common.collect.Maps;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.utils.DateUtils;
import com.cykj.common.utils.date.DateUtil;
import com.cykj.pos.domain.*;
import com.cykj.pos.service.*;
import com.cykj.system.service.ISysUserService;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author 许晓龙
 * @date 2025/1/21 15:43
 */
@Service
public class PosTransactionNoticeServiceImpl extends ServiceImpl<PosTransactionNoticeMapper, SynchronizationDataDTO> implements IPosTransactionNoticeService {

    @Autowired
    private PosTransactionNoticeMapper posTransactionNoticeMapper;

    @Autowired
    private IBizMerchTransactionsService bizMerchTransactionsService;

    @Autowired
    private IAllocationRelationService iAllocationRelationService;

    @Autowired
    private IBizTransactionAmount bizTransactionAmount;

    @Autowired
    private IAizProfitSharingRecordService iAizProfitSharingRecordService;

    @Autowired
    private IBizMerchantService bizMerchantService;

    @Autowired
    private IBizPosMachineService bizPosMachineService;

    @Resource
    private IBizWalletNewService bizWalletNewService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private IBizFeesChargedService bizFeesChargedService;

    @Resource
    private IBizPosMachineStatusRecordsService bizPosMachineStatusRecordsService;

    @Resource
    private BizMerchantInfoMapper bizMerchantInfoMapper;

    @Resource
    private BizPosMachineStatusRecordsMapper machineStatusRecordsMapper;

    @Resource
    private BizPosMachineMapper bizPosMachineMapper;

    @Resource
    private IToolCashbackTemplateService toolCashbackTemplateService;

    @Resource
    private IAizDeductionRecordsService iAizDeductionRecordsService;

    @Resource
    private IAizWithdrawalProfitService iAizWithdrawalProfitService;

    @Resource
    private IAizStatisticalMerchantService iAizStatisticalMerchantService;

    @Resource
    private IPosTransactionNoticeService iPosTransactionNoticeService;

    @Resource
    private PosPCommonParamConfig PosPCommonParamConfig;

    @Resource
    private IAizDeductionRecordsService aizDeductionRecordsService;


    /**
     * 交易通知业务处理
     *
     * @param sy
     * @return
     */
    @Override
    @Transactional
    public Map<String, String> transact(SynchronizationDataDTO sy) {
        Map<String, String> map = new HashMap<>();
        boolean b = judge(sy);
        if (!b) {
            map.put("ret_code", "0");
            map.put("ret_msg", "已有该笔交易");
            System.out.println("----交易已存在------");
            System.out.println("----------");
            return map;
        }
        // 储存交易
        String uuid = bizTransactionAmount.insertBizTransactionAmount(sy);
        sy.setUuid(uuid);
        if (!"00".equals(sy.getHost_ret_code())){
            map.put("ret_code", "0");
            map.put("ret_msg", "交易成功");
            System.out.println("----失败交易------"+JSONObject.toJSONString(sy));
            System.out.println("----------");
            return map;
        }
        //  累计商户交易量
        BizMerchantInfo bizMerchantInfo = bizMerchantInfoMapper.getMerchantInfoByMerchantCode(sy.getMerchant_no());
        bizMerchantInfo.setMerchantCode(sy.getMerchant_no());
        BigDecimal bigDecimal = new BigDecimal(sy.getAmnount());
        bizMerchantInfo.setTodayTransAmount(bizMerchantInfo.getTodayTransAmount().add(bigDecimal)); // 今日
        bizMerchantInfo.setThisMonthTransAmount(bizMerchantInfo.getThisMonthTransAmount().add(bigDecimal)); // 本月
        bizMerchantInfo.setThisYearTransAmount(bizMerchantInfo.getThisYearTransAmount().add(bigDecimal)); // 今年
        bizMerchantInfo.setTotalTransAmount(bizMerchantInfo.getTotalTransAmount().add(bigDecimal)); // 累计
        bizMerchantInfoMapper.updateMerchantsInfoByMerchantCode(bizMerchantInfo);
//        /****by tzf* 根据设备政策给代理返现  返到机具返现钱包 商户刷满给直属代理返 ***********************************/
        try{



            BizPosMachine posMachineBySnCode = bizPosMachineService.getPosMachineBySnCode(sy.getPos_sn());
            if(posMachineBySnCode.getCustomerCashBackId() != null){
                BizMerchantInfo info = bizMerchantInfoMapper.getMerchantInfoByMerchantCode(sy.getMerchant_no());
                if("0".equals(info.getCustomerCashBackStatus())){// 未返
                    //查看本次交易额+商户累计交易额是否大于模板金额
                    //查政策
                    CustomerCashBackTemp customerCashBackTemp = bizPosMachineService.getCCBTPolicy(posMachineBySnCode.getCustomerCashBackId());
                    // 累计交易额
                    BigDecimal totalAmount = new BigDecimal(sy.getAmnount()).add(new BigDecimal(info.getCustomerCashBackTotalAmount()));
                    if(totalAmount.compareTo(new BigDecimal(customerCashBackTemp.getCashAmount())) > 0){
                        // 1.产生记录
                        BizFeesCharged bizFeesCharged = new BizFeesCharged();
                        bizFeesCharged.setMamountId(IdWorker.getIdStr());
                        bizFeesCharged.setOrgnname(String.valueOf(posMachineBySnCode.getMerchId()));
                        bizFeesCharged.setMerchantNo(sy.getMerchant_no());
                        bizFeesCharged.setSn(posMachineBySnCode.getPosCode());
                        bizFeesCharged.setSimcardfee(String.valueOf(customerCashBackTemp.getBackAmount()));
                        bizFeesCharged.setMamountStarts("1");
                        bizFeesCharged.setAmtType("2");
                        bizFeesCharged.setUuid(sy.getUuid());
                        bizFeesCharged.setChannel(sy.getChannel());
                        bizFeesCharged.setRmbStatus("2");
                        bizFeesCharged.setHostDate(sy.getHost_date());
                        bizFeesCharged.setCreateTime(DateUtil.getBaiDuTime());
                        bizFeesChargedService.insertBizFeesCharged(bizFeesCharged);
                        // 2.给直属代理返现  给到奖励钱包  也就是提现分润钱包
                        SysUser user = sysUserService.selectUserByMerchId(posMachineBySnCode.getMerchId());
                        AizWithdrawalWallet aizWithdrawalWallet = bizWalletNewService.getWithdrawalWalletByUserId(user.getUserId(),Long.parseLong(sy.getChannel()));
                        if(aizWithdrawalWallet == null){
                            AizWithdrawalWallet aizWithdrawalWallet_new = new AizWithdrawalWallet();
                            aizWithdrawalWallet_new.setDeptId(user.getDeptId());
                            aizWithdrawalWallet_new.setDeptName(user.getDeptName());
                            aizWithdrawalWallet_new.setUserId(user.getUserId());
                            aizWithdrawalWallet_new.setAmount(new BigDecimal(customerCashBackTemp.getBackAmount()));
                            aizWithdrawalWallet_new.setChannelId(Long.parseLong(sy.getChannel()));
                            BizChannel bizChannel = bizPosMachineMapper.getChannelByChannelId(sy.getChannel());
                            aizWithdrawalWallet_new.setChannelName(bizChannel.getChannelName());
                            aizWithdrawalWallet_new.setCreateTime(DateUtil.getBaiDuTime());
                            bizWalletNewService.insertWithdrawalWallet(aizWithdrawalWallet_new);
                        }else{
                            aizWithdrawalWallet.setAmount(aizWithdrawalWallet.getAmount().add(new BigDecimal(customerCashBackTemp.getBackAmount())));
                            bizWalletNewService.updateWithdrawalWallet(aizWithdrawalWallet);
                        }
                        // 3.更新商户表状态
                        info.setCustomerCashBackStatus("1");
                        bizMerchantInfoMapper.updateCustomerCashBackStatus(info);
                        System.out.println("交易大于模板交易额,本次返"+info.getPosCode());
                    }else{
                        info.setCustomerCashBackTotalAmount(Double.valueOf(new BigDecimal(info.getCustomerCashBackTotalAmount()).add(new BigDecimal(sy.getAmnount())).toString()));
                        bizMerchantInfoMapper.updateCustomerCashBackTotalAmount(info);
                        System.out.println("交易未大于模板交易额,本次不返"+info.getPosCode());
                    }
                }
            }

        }catch (Exception e){
            System.out.println(e.getMessage());
        }
//        /****************************************/

        LambdaQueryWrapper<AllocationRelation> lqw = Wrappers.lambdaQuery();
        lqw.eq(AllocationRelation::getPosSn, sy.getPos_sn());
        // 查询出结算费率和关系倒叙
        List<AllocationRelation> list = iAllocationRelationService.list(lqw.orderByDesc(AllocationRelation::getLevel));
        // 算账分润
        return settleAccounts(list, sy);
    }

    @Override
    @Transactional
    public Map deposit(SynchronizationDataDTO sy) {
        Map<String, String> map = new HashMap<>();
        // 交易是否存在
        boolean b = judge(sy);
        if (!b) {
            map.put("ret_code", "0");
            map.put("ret_msg", "已有该笔交易");
            System.out.println("----交易已存在------");
            System.out.println("----------");
            return map;
        }
        // 储存交易
        String uuid = bizTransactionAmount.insertBizTransactionAmount(sy);
        sy.setUuid(uuid);
        LambdaQueryWrapper<AllocationRelation> lqw = Wrappers.lambdaQuery();
        lqw.eq(AllocationRelation::getPosSn, sy.getPos_sn());
        // 查询出结算费率和关系倒叙
        List<AllocationRelation> list = iAllocationRelationService.list(lqw.orderByDesc(AllocationRelation::getLevel));
        String isTwo = "0"; // 首次
        // 2 插入返现记录
        feeCharged(list, sy, "1", isTwo);
        // 3 钱包打钱
        cashback(list, sy, "1", isTwo);
        // 更新激活时间
        list.stream().forEach(e -> {
            e.setActiveTime(com.cykj.pos.util.DateUtils.dateFormatString(DateUtil.getBaiDuTime()));
            iAllocationRelationService.updateById(e);
        });
        map.put("ret_code", "0");
        map.put("ret_msg", "交易成功");
        return map;
    }

    @Override
    @Transactional
    public Map simFee(SynchronizationDataDTO sy) {
        Map<String, String> map = new HashMap<>();
        map.put("ret_code", "0");
        map.put("ret_msg", "交易成功");
        // 交易是否存在
        boolean b = judge(sy);
        if (!b) {
            map.put("ret_code", "0");
            map.put("ret_msg", "已有该笔交易");
            System.out.println("----交易已存在------");
            System.out.println("----------");
            return map;
        }
        // 储存交易
        String uuid = bizTransactionAmount.insertBizTransactionAmount(sy);
        sy.setUuid(uuid);
        Double amnount = sy.getAmnount();
        BigDecimal sim = new BigDecimal(amnount);
        LambdaQueryWrapper<AllocationRelation> lqw = Wrappers.lambdaQuery();
        lqw.eq(AllocationRelation::getPosSn, sy.getPos_sn());
        // 查询出结算费率和关系倒叙
        List<AllocationRelation> list = iAllocationRelationService.list(lqw.orderByDesc(AllocationRelation::getLevel));
        BizPosMachine bizPosMachine = bizPosMachineService.selectPosBySnCode(sy.getPos_sn());
        if ("0".equals(bizPosMachine.getVar5())) {  // 无押机器
            // 更新激活时间
            list.stream().forEach(e -> {
                e.setActiveTime(com.cykj.pos.util.DateUtils.dateFormatString(DateUtil.getBaiDuTime()));
                iAllocationRelationService.updateById(e);
            });
        }
        list.stream().forEach(e->{
            // 取档位
            if (sim.compareTo(new BigDecimal("48")) == 0) {
                e.setSimFee(e.getFortyEight());
                System.out.println("取到48档位-------"+e.getPosSn());
            }else if (sim.compareTo(new BigDecimal("58")) == 0){
                e.setSimFee(e.getFiftyEight());
                System.out.println("取到58档位-------"+e.getPosSn());
            }else if (sim.compareTo(new BigDecimal("60")) == 0){
                e.setSimFee(e.getSixty());
                System.out.println("取到60档位-------"+e.getPosSn());
            }else if (sim.compareTo(new BigDecimal("68")) == 0){
                e.setSimFee(e.getSixtyEight());
                System.out.println("取到68档位-------"+e.getPosSn());
            }else if (sim.compareTo(new BigDecimal("77")) == 0){
                e.setSimFee(e.getSeventySeven());
                System.out.println("取到77档位-------"+e.getPosSn());
            }else if (sim.compareTo(new BigDecimal("78")) == 0){
                e.setSimFee(e.getSeventyEight());
                System.out.println("取到78档位-------"+e.getPosSn());
            }else if (sim.compareTo(new BigDecimal("88")) == 0){
                e.setSimFee(e.getEightyEight());
                System.out.println("取到88档位-------"+e.getPosSn());
            }else if (sim.compareTo(new BigDecimal("98")) == 0){
                e.setSimFee(e.getNinetyEight());
                System.out.println("取到98档位-------"+e.getPosSn());
            }else if (sim.compareTo(new BigDecimal("99")) == 0){
                e.setSimFee(e.getNinetyNine());
                System.out.println("取到99档位-------"+e.getPosSn());
            }else {
                System.out.println(sim+"什么档位也没取到-------"+e.getPosSn());
            }
        });
        // 查询流量费收取列表
        int i = bizFeesChargedService.selectIsSecondSimAmt(sy.getMerchant_no(), sy.getPos_sn());
        String isTwo = "0"; // 首次
  //      if (i > 0) { //收取过流量费  查看机器政策是否是循环返现     2025-04-26 （修改不要二次了）
   //         isTwo = "1";
        // 判断是否循环
            ToolCashbackTemplate byId = toolCashbackTemplateService.getById(bizPosMachine.getCashbackId());
            if (byId != null){
                if ("0".equals(byId.getCircularCashback())) {  // 不循环
                    return map;
                }
            }
    //    }

        // 流量费记录
        feeCharged(list, sy, "0", isTwo);
        // 钱包打钱
        cashback(list, sy, "0", isTwo);
        return map;
    }

    /**
     * 查询交易明细
     *
     * @param detailsDTO
     * @return
     */
    @Override
    @Transactional
    public AjaxResult transactionDetails(TransactionDetailsDTO detailsDTO) {

        Long userId = LoginUserUtils.getLoginUserId();
        BizMerchant merchant = bizMerchantService.getMerchantByUserId(userId);
        detailsDTO.setMerchId(merchant.getMerchId());
        // 处理分页
        if (detailsDTO.getPageNo() != -1 && detailsDTO.getPageSize() != -1) {
            int start = (detailsDTO.getPageNo() - 1) * detailsDTO.getPageSize();
            detailsDTO.setStartPage(start);
        }
        if (StringUtils.isEmpty(detailsDTO.getStartTime()) && StringUtils.isEmpty(detailsDTO.getEndTime())) {
            detailsDTO.setStartTime(DateUtils.getTime());
            detailsDTO.setEndTime(DateUtils.getTime());
        }
        String startTime = detailsDTO.getStartTime();
        String endTime = detailsDTO.getEndTime();
        startTime = startTime.substring(0, 10) + " " + "00:00:00";
        endTime = endTime.substring(0, 10) + " " + "23:59:59";
        detailsDTO.setStartTime(startTime);
        detailsDTO.setEndTime(endTime);
        if (StringUtils.isNotEmpty(detailsDTO.getPosSn())) {
            boolean b = IschineseByutil.ischineseByutil(detailsDTO.getPosSn());
            if (b) {
                detailsDTO.setCupsName(detailsDTO.getPosSn());
                detailsDTO.setPosSn(null);
            }
        }
        /*****************add by tzf**********************/
        if ("3".equals(detailsDTO.getTransType())) {
            detailsDTO.setUserId(userId);// 3 奖励钱包
            return iAizWithdrawalProfitService.appBackWithdrawalProfitRecords(detailsDTO);
        } else if ("4".equals(detailsDTO.getTransType())) {// 4 扣款钱包
            return iAizDeductionRecordsService.appBackDeductionRecords(detailsDTO);
        }
        /*****************add by tzf*********************/
        // 交易明细：商户名称，分润金额，交易金额，时间    传参：渠道，代理id
        List<TranscationListDTO> dtolist = posTransactionNoticeMapper.selectTransactionDetails(detailsDTO);
        List<TranscationListDTO> dtolistUp = posTransactionNoticeMapper.selectTransactionDetailsUp(detailsDTO);

        dtolist.stream().forEach(e -> {
            // 查询分润
            if ("1".equals(detailsDTO.getTransType())) {
                LambdaQueryWrapper<AizProfitSharingRecord> lambdaQueryWrapper = Wrappers.lambdaQuery();
                lambdaQueryWrapper.eq(AizProfitSharingRecord::getUuid, e.getUuid());
                lambdaQueryWrapper.eq(AizProfitSharingRecord::getMerchId, detailsDTO.getMerchId());
                if (StringUtils.isNotEmpty(detailsDTO.getChannel())){
                    lambdaQueryWrapper.eq(AizProfitSharingRecord::getChannel, detailsDTO.getChannel());
                }
                AizProfitSharingRecord one = iAizProfitSharingRecordService.getOne(lambdaQueryWrapper);
                if (one == null) {
                    e.setProfitSharingAmount(0.00); // 分润金额
                } else {
                    e.setProfitSharingAmount(Double.parseDouble(one.getShareAmount().toString())); // 分润金额
                }
            } else if ("2".equals(detailsDTO.getTransType())) { // 查询返现
                LambdaQueryWrapper<BizFeesCharged> lqw = Wrappers.lambdaQuery();
                lqw.eq(BizFeesCharged::getUuid, e.getUuid());
                lqw.eq(BizFeesCharged::getOrgnname, detailsDTO.getMerchId());
                if (StringUtils.isNotEmpty(detailsDTO.getChannel())){
                    lqw.eq(BizFeesCharged::getChannel, detailsDTO.getChannel());
                }
                BizFeesCharged one = bizFeesChargedService.getOne(lqw);
                if (one != null) {
                   // detailsDTO.setNumber(detailsDTO.getNumber() + 1); // 返现笔数
                    e.setProfitSharingAmount(Double.parseDouble(one.getSimcardfee())); // 返现金额
                } else {
                    e.setProfitSharingAmount(0.00); // 返现金额
                }
            }
        });
        detailsDTO.setDtolist(dtolist);
        if ("1".equals(detailsDTO.getTransType())) {
            // 总交易额日期筛选
            double transactionAmount = dtolistUp.stream().mapToDouble(TranscationListDTO::getTransactionAmount).sum();
          //  double profitSharingAmount = dtolist.stream().mapToDouble(TranscationListDTO::getProfitSharingAmount).sum();
            LambdaQueryWrapper<AizProfitSharingRecord> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(AizProfitSharingRecord::getMerchId, detailsDTO.getMerchId());
            if (StringUtils.isNotEmpty(detailsDTO.getChannel())){
                lambdaQueryWrapper.eq(AizProfitSharingRecord::getChannel, detailsDTO.getChannel());
            }
            lambdaQueryWrapper.between(AizProfitSharingRecord::getHostDate,startTime,endTime);
            // 总分润
            List<AizProfitSharingRecord> list = iAizProfitSharingRecordService.list(lambdaQueryWrapper);
            double profitSharingAmount = list.stream().map(e->e.getShareAmount()).reduce(BigDecimal.ZERO,BigDecimal::add).doubleValue();

            int size = list.size();
            detailsDTO.setNumber(size); // 时间条件筛选收益笔数
            detailsDTO.setTransactionAmount(transactionAmount); // 总交易额
            detailsDTO.setProfitSharingAmount(profitSharingAmount); // 时间筛选任润
        } else if ("2".equals(detailsDTO.getTransType())) { // 返现
          //  double cashbackAmount = dtolist.stream().mapToDouble(TranscationListDTO::getProfitSharingAmount).sum();
            // 累计返现
            BizFeesCharged bizFeesCharged = bizFeesChargedService.selectCashbackAmountAll(merchant.getMerchId(), detailsDTO.getChannel());
            // 时间筛选返现
            BizFeesCharged bizFeesChargedUp = bizFeesChargedService.selectCashbackAmountAllUp(merchant.getMerchId(), detailsDTO.getChannel(),startTime,endTime);
            detailsDTO.setNumber(bizFeesChargedUp.getNum());
            detailsDTO.setTransactionAmount(bizFeesChargedUp.getTotalAmount()); // 累计返现 时间筛选
            detailsDTO.setProfitSharingAmount(bizFeesChargedUp.getTotalAmount()); // 返现
        }
        System.out.println("****************" + detailsDTO);
        AjaxResult ajaxResult = AjaxResult.success(detailsDTO);
        return ajaxResult;
    }

    @Override
    public AjaxResult todayStatistics(TransactionDetailsDTO detailsDTO) {
        AjaxResult ajaxResult = AjaxResult.success();
        JSONObject result = new JSONObject();
        Long userId = LoginUserUtils.getLoginUserId();
        BizMerchant merchant = bizMerchantService.getMerchantByUserId(userId);
        detailsDTO.setMerchId(merchant.getMerchId());
        // 查询激活数
        detailsDTO.setTodayTime(com.cykj.pos.util.DateUtils.dateFormatStringToo(new Date()));
        int count = bizPosMachineStatusRecordsService.selectActiveCount(detailsDTO);
        Double amountToday = posTransactionNoticeMapper.todayStatistics(detailsDTO);
        Double share = iAizProfitSharingRecordService.selectShare(detailsDTO);
        result.put("activeNum", count); // 今日激活数 自身
        result.put("amountToday", amountToday); // 今日交易额 自身
        result.put("share", share); // 今日交易额 自身
        ajaxResult.put("result", result);
        return ajaxResult;
    }

    @Override
    public AjaxResult homePageData(TransactionDetailsDTO detailsDTO) {
        AjaxResult ajaxResult = AjaxResult.success();
        Long userId = LoginUserUtils.getLoginUserId();
        BizMerchant merchant = bizMerchantService.getMerchantByUserId(userId);
        if (merchant == null) {
            ajaxResult = AjaxResult.success("当前用户未入驻商户");
            ajaxResult.put("code", "500001");
            return ajaxResult;
        }
        Long merchId = merchant.getMerchId();
        HomePageDataDTO dataVo = new HomePageDataDTO();
        if ("1".equals(detailsDTO.getType())) {  // 总计
            dataVo = this.selectHomeData(merchId, userId);
        } else if ("2".equals(detailsDTO.getType())) { //  今日
            dataVo = this.selectHomeDataToday(merchId, userId);
        }
        dataVo.setMerchCode(merchant.getMerchCode());
        // 腾讯接口对接用的常量
        dataVo.setSecretId(CommEnum.SECRETID.getValue());
        dataVo.setSecretKey(CommEnum.SECRETKEY.getValue());
        dataVo.setBucketName(CommEnum.BUCKETNAME.getValue());
        // 客服电话
        dataVo.setServicePhone(CommEnum.SERVICE_PHONE.getValue());
        // 设置头像
        // dataVo.setPortrait(sysUser.getPortrait());
        ajaxResult.put("data", dataVo);
        return ajaxResult;
    }

    @Override
    public HomePageDataDTO selectHomeData(Long merchId, Long userId) {
        String formatedDate = com.cykj.pos.util.DateUtils.getCaculateYearAndMonth("", "yyyy-MM");
        HomePageDTO homePageDTO = new HomePageDTO();
        homePageDTO.setMerchId(merchId);
        homePageDTO.setYearMonth(formatedDate);
        homePageDTO.setUserId(userId);
        return posTransactionNoticeMapper.selectHomeData(homePageDTO);
    }

    @Override
    public HomePageDataDTO selectHomeDataToday(Long merchId, Long userId) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formatedDate = simpleDateFormat.format(new Date());
        HomePageDTO homePageDTO = new HomePageDTO();
        homePageDTO.setMerchId(merchId);
        homePageDTO.setYearMonth(formatedDate);
        homePageDTO.setUserId(userId);
        return posTransactionNoticeMapper.selectHomeDataToday(homePageDTO);
    }

    @Override
    public List<PartnerDetailDTO> numberOfTeamTransaction(MerchantDTO merchantDTO) {

        List<PartnerDetailDTO> list = new ArrayList<PartnerDetailDTO>();
        BigDecimal bigDecimal = new BigDecimal("0");
  /*      Long userId = LoginUserUtils.getLoginUserId();
        BizMerchant merchant = bizMerchantService.getMerchantByUserId(userId);
        merchantDTO.setMerchId(merchant.getMerchId());// 存入merch_id*/
        Date date = new Date();// 当前时间
        if (merchantDTO.getSignAmount() == 1) {// 交易额按一周查
            // 先写出一周的时间
            for (int i = 0; i < 7; i++) {
                String time = com.cykj.pos.util.DateUtils.dateSubOne(date, -i - 1);// 循环查出一周时间
                merchantDTO.setMonthType(time);// 把时间条件存进去
                PartnerDetailDTO partnerDetailDTO = posTransactionNoticeMapper.getPartnerAmountStatistical(merchantDTO);
                if (partnerDetailDTO == null) {
                    PartnerDetailDTO partnerDetailDTO1 = new PartnerDetailDTO();
                    partnerDetailDTO1.setMoney(bigDecimal);
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutDate(time, 1);
                    partnerDetailDTO1.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO1);
                }
                if (partnerDetailDTO != null) {
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutDate(time, 1);
                    partnerDetailDTO.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO);
                }
            }
            Collections.reverse(list);
            return list;
        }
        if (merchantDTO.getSignAmount() == 2) {// 交易额按半年查
            // 先查出半年的时间
            for (int i = 0; i < 6; i++) {
                String time = com.cykj.pos.util.DateUtils.dateSubMonth(date, -i - 1);
                merchantDTO.setMonthType(time);
                PartnerDetailDTO partnerDetailDTO = posTransactionNoticeMapper.getPartnerAmountStatistical(merchantDTO);
                if (partnerDetailDTO == null) {
                    PartnerDetailDTO partnerDetailDTO1 = new PartnerDetailDTO();
                    partnerDetailDTO1.setMoney(bigDecimal);
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutMonth(time, 2);
                    partnerDetailDTO1.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO1);
                }
                if (partnerDetailDTO != null) {
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutMonth(time, 2);
                    partnerDetailDTO.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO);
                }
            }
            Collections.reverse(list);
            return list;
        }
        return null;


    }

    @Override
    public List<PartnerDetailDTO> numberOfTeamActivations(MerchantDTO merchantDTO) {
        List<PartnerDetailDTO> list = new ArrayList<PartnerDetailDTO>();
        BigDecimal bigDecimal = new BigDecimal("0");
        int activeNum = 0;
    /*    Long userId = LoginUserUtils.getLoginUserId();
        BizMerchant merchant = bizMerchantService.getMerchantByUserId(userId);
        merchantDTO.setMerchId(merchant.getMerchId());// 存入merch_id*/
        Date date = new Date();// 当前时间
        if (merchantDTO.getSignAmount() == 1) {// 交易额按一周查
            // 先写出一周的时间
            for (int i = 0; i < 7; i++) {
                String time = com.cykj.pos.util.DateUtils.dateSubOne(date, -i - 1);// 循环查出一周时间
                merchantDTO.setMonthType(time);// 把时间条件存进去
                PartnerDetailDTO partnerDetailDTO = posTransactionNoticeMapper.selectActiveSeven(merchantDTO);
                if (partnerDetailDTO == null) {
                    PartnerDetailDTO partnerDetailDTO1 = new PartnerDetailDTO();
                    partnerDetailDTO1.setActiveNum(activeNum);
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutDate(time, 1);
                    partnerDetailDTO1.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO1);
                }
                if (partnerDetailDTO != null) {
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutDate(time, 1);
                    partnerDetailDTO.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO);
                }
            }
            Collections.reverse(list);
            return list;
        }
        if (merchantDTO.getSignAmount() == 2) {// 交易额按半年查
            // 先查出半年的时间
            for (int i = 0; i < 6; i++) {
                String time = com.cykj.pos.util.DateUtils.dateSubMonth(date, -i - 1);
                merchantDTO.setMonthType(time);
                PartnerDetailDTO partnerDetailDTO = posTransactionNoticeMapper.selectActiveSeven(merchantDTO);
                if (partnerDetailDTO == null) {
                    PartnerDetailDTO partnerDetailDTO1 = new PartnerDetailDTO();
                    partnerDetailDTO1.setActiveNum(activeNum);
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutMonth(time, 2);
                    partnerDetailDTO1.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO1);
                }
                if (partnerDetailDTO != null) {
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutMonth(time, 2);
                    partnerDetailDTO.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO);
                }
            }
            Collections.reverse(list);
            return list;
        }
        return null;
    }

    @Override
    public AjaxResult homePageTradeIncomeActivate(TransactionDetailsDTO detailsDTO) {
        AjaxResult ajaxResult = AjaxResult.success();
        Long userId = LoginUserUtils.getLoginUserId();
        BizMerchant merchant = bizMerchantService.getMerchantByUserId(userId);
        if (merchant == null) {
            ajaxResult = AjaxResult.success("当前用户未入驻商户");
            ajaxResult.put("code", "500001");
            return ajaxResult;
        }
        Long merchId = merchant.getMerchId();
        HomePageDataDTO dataVo = new HomePageDataDTO();
        if ("1".equals(detailsDTO.getType())) {  // 交易
            dataVo = this.selectHomeDataTranscation(merchId, userId,detailsDTO.getChannel());
        } else if ("2".equals(detailsDTO.getType())) { //  收益
            dataVo = this.selectHomeDataProfit(merchId, userId,detailsDTO.getChannel());
        } else if ("3".equals(detailsDTO.getType())) { //  激活
            dataVo = this.selectHomeDataActive(merchId, userId,detailsDTO.getChannel());
        }else {
            return AjaxResult.error("参数错误");
        }
        dataVo.setNickName(merchant.getMerchName());
        dataVo.setMerchCode(merchant.getMerchCode());
        // 腾讯接口对接用的常量
        dataVo.setSecretId(CommEnum.SECRETID.getValue());
        dataVo.setSecretKey(CommEnum.SECRETKEY.getValue());
        dataVo.setBucketName(CommEnum.BUCKETNAME.getValue());
        // 客服电话
        dataVo.setServicePhone(CommEnum.SERVICE_PHONE.getValue());
        // 设置头像
        // dataVo.setPortrait(sysUser.getPortrait());
        ajaxResult.put("data", dataVo);
        return ajaxResult;
    }

    @Override
    public HomePageDataDTO selectHomeDataTranscation(Long merchId, Long userId, String channel) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formatedDate = simpleDateFormat.format(new Date());
        HomePageDTO homePageDTO = new HomePageDTO();
        homePageDTO.setMerchId(merchId);
        homePageDTO.setYearMonth(formatedDate);
        homePageDTO.setUserId(userId);
        homePageDTO.setChannel(channel);
        return posTransactionNoticeMapper.selectHomeDataTranscation(homePageDTO);
    }

    @Override
    public HomePageDataDTO selectHomeDataProfit(Long merchId, Long userId,String channel) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formatedDate = simpleDateFormat.format(new Date());
        HomePageDTO homePageDTO = new HomePageDTO();
        homePageDTO.setMerchId(merchId);
        homePageDTO.setYearMonth(formatedDate);
        homePageDTO.setUserId(userId);
        homePageDTO.setChannel(channel);
        return posTransactionNoticeMapper.selectHomeDataProfit(homePageDTO);
    }

    @Override
    public HomePageDataDTO selectHomeDataActive(Long merchId, Long userId,String channel) {
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(new Date());
        rightNow.add(Calendar.DAY_OF_MONTH,-1 );
        Date dt1 = rightNow.getTime(); // 昨日
        Calendar Now = Calendar.getInstance();
        Now.setTime(new Date());
        Now.add(Calendar.MONTH,-1 );
        Date lastMONTH = Now.getTime(); // 上月
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        String formatedDate = simpleDateFormat.format(new Date());
        HomePageDTO homePageDTO = new HomePageDTO();
        homePageDTO.setMerchId(merchId);
        homePageDTO.setYearMonth(formatedDate); // 本月
        homePageDTO.setYesterday(DateUtils.dateTime(dt1));
        homePageDTO.setToday(DateUtils.dateTime(new Date()));
        homePageDTO.setLastMonth(simpleDateFormat.format(lastMONTH));
        homePageDTO.setUserId(userId);
        homePageDTO.setChannel(channel);
        return posTransactionNoticeMapper.selectHomeDataActive(homePageDTO);
    }

    @Override
    public AjaxResult homePageTeamOverview(TeamOverviewDTO teamOverviewDTO) {
        AjaxResult ajaxResult = new AjaxResult();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM");
        double lastMonthTransAmountSum = 0.00; // 上月交易额
        double totalTransAmountSum = 0.00;  // 总交易额
        double lastMonthProfitAmountSum = 0.00; // 上月总收益
        double totalProfitAmountSum = 0.00; // 总收益
        int posNum = 0; // 交易设备数量
        BigDecimal divideTrans = new BigDecimal(0.00);

        BigDecimal divideProfit = new BigDecimal(0.00);

        // 查询交易
        Long userId = LoginUserUtils.getLoginUserId();
        BizMerchant merchant = bizMerchantService.getMerchantByUserId(userId);
        if (merchant == null) {
            ajaxResult = AjaxResult.success("当前用户未入驻商户");
            ajaxResult.put("code", "500001");
            return ajaxResult;
        }
        MerchantDTO merchantDTO = new MerchantDTO();
        merchantDTO.setMerchId(merchant.getMerchId());
        merchantDTO.setChannel(teamOverviewDTO.getChannel());
        merchantDTO.setSignAmount(teamOverviewDTO.getSignAmount());
        LambdaQueryWrapper<AizStatisticalMerchant> lambdaQueryWrapper =  Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(AizStatisticalMerchant::getUserId,userId);
     //   if ("1".equals(teamOverviewDTO.getRequestType()) || "2".equals(teamOverviewDTO.getRequestType())){ // 交易和收益一起查出来
            if (StringUtils.isNotEmpty(teamOverviewDTO.getChannel())){ // 单个渠道
                lambdaQueryWrapper.eq(AizStatisticalMerchant::getChannelId,teamOverviewDTO.getChannel());
                // 总交易金额 上月交易金额
                AizStatisticalMerchant one = iAizStatisticalMerchantService.getOne(lambdaQueryWrapper);
                lastMonthTransAmountSum = one.getLastMonthTransAmount();
                totalTransAmountSum = one.getTotalTransAmount();
                lastMonthProfitAmountSum = one.getLastMonthProfitAmount();
                totalProfitAmountSum = one.getTotalProfitAmount();
                //  iAizStatisticalMerchantService.list(lambdaQueryWrapper).stream().mapToDouble(AizStatisticalMerchant::getTransactionAmount).sum();
            }else { // 全渠道
                List<AizStatisticalMerchant> list = iAizStatisticalMerchantService.list(lambdaQueryWrapper);
                // 上月交易额
                lastMonthTransAmountSum = list.stream().mapToDouble(AizStatisticalMerchant::getLastMonthTransAmount).sum();
                // 总交易额
                totalTransAmountSum = list.stream().mapToDouble(AizStatisticalMerchant::getTotalTransAmount).sum();
                // 总收益
                totalProfitAmountSum = list.stream().mapToDouble(AizStatisticalMerchant::getTotalProfitAmount).sum();
                // 上月总收益
                lastMonthProfitAmountSum = list.stream().mapToDouble(AizStatisticalMerchant::getLastMonthProfitAmount).sum();
            }
    //    }
        //  查询台均交易额
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        Date lastMonth = calendar.getTime();
        String format = sdf.format(lastMonth);
        String thisMonth = "";
        // 交易笔数
        int transNum = posTransactionNoticeMapper.selectTransCount(merchant.getMerchId(),teamOverviewDTO.getChannel(),format);
        // 上月多少台机器交易
        posNum = posTransactionNoticeMapper.selectPosTrans(merchant.getMerchId(),teamOverviewDTO.getChannel(),format);
        // 上月台均
        if (posNum != 0){
             divideTrans = new BigDecimal(lastMonthTransAmountSum).divide(new BigDecimal(posNum), 2, RoundingMode.DOWN);
        }
        teamOverviewDTO.setLastMonthTransAmount(new BigDecimal(lastMonthTransAmountSum).divide(new BigDecimal(10000),2,RoundingMode.DOWN));
        teamOverviewDTO.setLastMonthTransCount(transNum);
        teamOverviewDTO.setAverageLastMonthTransAmount(divideTrans.divide(new BigDecimal(10000),2,RoundingMode.DOWN));
        teamOverviewDTO.setTotalTransAmountSum(new BigDecimal(totalTransAmountSum).divide(new BigDecimal(10000),2,RoundingMode.DOWN));

        // 查询分润笔数
        int profitCountNum = posTransactionNoticeMapper.selectProfitCount(merchant.getMerchId(),teamOverviewDTO.getChannel(),format);
        // 有分润的机器是多少
        int profitPosNum = posTransactionNoticeMapper.selectPosProfit(merchant.getMerchId(),teamOverviewDTO.getChannel(),format);
        // 上月台均分润
        if (profitPosNum != 0){
             divideProfit = new BigDecimal(lastMonthProfitAmountSum).divide(new BigDecimal(profitPosNum), 2, RoundingMode.DOWN);
        }
        teamOverviewDTO.setProfitLastMonthCount(profitCountNum);
        teamOverviewDTO.setProfitTotal(new BigDecimal(totalProfitAmountSum).setScale(2,RoundingMode.DOWN).doubleValue());
        teamOverviewDTO.setLastMonthProfitAmount(new BigDecimal(lastMonthProfitAmountSum).setScale(2,RoundingMode.DOWN).doubleValue());
        teamOverviewDTO.setProfitAverageLastMonth(divideProfit.doubleValue());

        // 查询入库设备
        TeamOverviewDTO teamActive = bizPosMachineService.selectPosNumAndActiveNum(merchant.getMerchId(),teamOverviewDTO.getChannel(),format);
        teamOverviewDTO.setPosTotalCount(teamActive.getPosTotalCount());
        teamOverviewDTO.setTotalActiveNum(teamActive.getTotalActiveNum());
        teamOverviewDTO.setLastMonthActiveNum(teamActive.getLastMonthActiveNum());
        if (teamActive.getPosTotalCount() == 0){
            teamOverviewDTO.setActivationRate(0.00);
        }else {
            BigDecimal result =  new BigDecimal(teamActive.getTotalActiveNum()).divide(new BigDecimal(teamActive.getPosTotalCount()),2,RoundingMode.DOWN) ;
            teamOverviewDTO.setActivationRate(result.doubleValue());
        }
        if ("1".equals(teamOverviewDTO.getRequestType())){ // 查询交易
            // 交易柱状图
            List<PartnerDetailDTO> partnerDetailDTOList = iPosTransactionNoticeService.numberOfTeamTransaction(merchantDTO);
            teamOverviewDTO.setListTrans(partnerDetailDTOList);
            // 交易排行榜
            // 一支人的自身交易，交易额倒叙

            if ("1".equals(teamOverviewDTO.getTeamRankingType())){
                thisMonth = sdf.format(new Date());
            }
            List<TradingRankingDTO>  tradingRankingList = posTransactionNoticeMapper.selectTradingRanking(merchant.getMerchId(),teamOverviewDTO.getChannel(),thisMonth);

            IntStream.range(0, tradingRankingList.size()).forEach(e->{
             tradingRankingList.get(e).setRank(e+1);
         });
            teamOverviewDTO.setTradingRanking(tradingRankingList);
            boolean b = tradingRankingList.stream().anyMatch(tradingRankingDTO -> tradingRankingDTO.getMerchId() == merchant.getMerchId());
            if (b){
                TradingRankingDTO tradingRankingDTO1 = tradingRankingList.stream().filter(tradingRankingDTO -> tradingRankingDTO.getMerchId() == merchant.getMerchId()).findFirst().get();
                teamOverviewDTO.setMerchRank(tradingRankingDTO1.getRank());
            }else {
                teamOverviewDTO.setMerchRank(0); // 未上榜
            }
        }else if ("2".equals(teamOverviewDTO.getRequestType())){ // 查询收益
            // 收益柱状图
            List<PartnerDetailDTO> partnerDetailDTOList = iPosTransactionNoticeService.numberOfTeamincome(merchantDTO);
            teamOverviewDTO.setListIncome(partnerDetailDTOList);
            // 收益排行榜
            // 一支人的自身交易，交易额倒叙
            List<TradingRankingDTO> IncomeRankingList = new ArrayList<>();
            if (StringUtils.isNotEmpty(teamOverviewDTO.getChannel())){

                if ("1".equals(teamOverviewDTO.getTeamRankingType())){
                      IncomeRankingList = posTransactionNoticeMapper.selectTradingRankingIncomeDangYue(merchant.getMerchId(),teamOverviewDTO.getChannel(),thisMonth);
                }else {
                     IncomeRankingList = posTransactionNoticeMapper.selectTradingRankingIncome(merchant.getMerchId(),teamOverviewDTO.getChannel(),thisMonth);
                }
                List<TradingRankingDTO> finalIncomeRankingList1 = IncomeRankingList;
                IntStream.range(0, IncomeRankingList.size()).forEach(e->{
                    finalIncomeRankingList1.get(e).setRank(e+1);
                });
                IncomeRankingList = finalIncomeRankingList1;
                teamOverviewDTO.setIncomeRanking(IncomeRankingList);
                boolean b = IncomeRankingList.stream().anyMatch(in -> in.getMerchId() == merchant.getMerchId());

                if (b){
                    TradingRankingDTO tradingRankingDTO = IncomeRankingList.stream().filter(in -> in.getMerchId() == merchant.getMerchId()).findFirst().get();
                    teamOverviewDTO.setMerchRank(tradingRankingDTO.getRank());
                }else {
                    teamOverviewDTO.setMerchRank(0);
                }

            }else { // 全渠道
                if ("1".equals(teamOverviewDTO.getTeamRankingType())){
                    IncomeRankingList = posTransactionNoticeMapper.selectTradingRankingIncomeAllChannelDangYue(merchant.getMerchId(),teamOverviewDTO.getChannel(),format);
                }else {
                    IncomeRankingList = posTransactionNoticeMapper.selectTradingRankingIncomeAllChannel(merchant.getMerchId(),teamOverviewDTO.getChannel(),format);
                }
                List<TradingRankingDTO> finalIncomeRankingList = IncomeRankingList;
                IntStream.range(0, IncomeRankingList.size()).forEach(e->{
                    finalIncomeRankingList.get(e).setRank(e+1);
                });
                IncomeRankingList =  finalIncomeRankingList;
                teamOverviewDTO.setIncomeRanking(IncomeRankingList);
                boolean b = IncomeRankingList.stream().anyMatch(in -> in.getMerchId() == merchant.getMerchId());
                if (b){
                    TradingRankingDTO tradingRankingDTO = IncomeRankingList.stream().filter(in -> in.getMerchId() == merchant.getMerchId()).findFirst().get();
                    teamOverviewDTO.setMerchRank(tradingRankingDTO.getRank());
                }else {
                    teamOverviewDTO.setMerchRank(0);
                }

            }
        }else if ("3".equals(teamOverviewDTO.getRequestType())){  //  激活
            // 激活柱状图
            List<PartnerDetailDTO> partnerDetailDTOList = iPosTransactionNoticeService.numberOfTeamActivations(merchantDTO);
            teamOverviewDTO.setListActive(partnerDetailDTOList);
            // 激活排行榜
            if ("1".equals(teamOverviewDTO.getTeamRankingType())){
                thisMonth = sdf.format(new Date());
            }
            List<TradingRankingDTO>  ActiveRankingList = posTransactionNoticeMapper.selectActiveRanking(merchant.getMerchId(),teamOverviewDTO.getChannel(),thisMonth);
            IntStream.range(0, ActiveRankingList.size()).forEach(e->{
                ActiveRankingList.get(e).setRank(e+1);
            });
            teamOverviewDTO.setActiveRanking(ActiveRankingList);
            boolean b = ActiveRankingList.stream().anyMatch(ac -> ac.getMerchId() == merchant.getMerchId());
            if (b){
                TradingRankingDTO tradingRankingDTO = ActiveRankingList.stream().filter(ac -> ac.getMerchId() == merchant.getMerchId()).findFirst().get();
                teamOverviewDTO.setMerchRank(tradingRankingDTO.getRank());
            }else {
                teamOverviewDTO.setMerchRank(0);
            }
        }
        ajaxResult = AjaxResult.success(teamOverviewDTO);
         return  ajaxResult;

    }

    @Override
    public List<PartnerDetailDTO> numberOfTeamincome(MerchantDTO merchantDTO) {
        List<PartnerDetailDTO> list = new ArrayList<PartnerDetailDTO>();
        BigDecimal bigDecimal = new BigDecimal("0");
        int activeNum = 0;
    /*    Long userId = LoginUserUtils.getLoginUserId();
        BizMerchant merchant = bizMerchantService.getMerchantByUserId(userId);
        merchantDTO.setMerchId(merchant.getMerchId());// 存入merch_id*/
        Date date = new Date();// 当前时间
        if (merchantDTO.getSignAmount() == 1) {// 交易额按一周查
            // 先写出一周的时间
            for (int i = 0; i < 7; i++) {
                String time = com.cykj.pos.util.DateUtils.dateSubOne(date, -i - 1);// 循环查出一周时间
                merchantDTO.setMonthType(time);// 把时间条件存进去
                PartnerDetailDTO partnerDetailDTO = posTransactionNoticeMapper.selectIncome(merchantDTO);
                if (partnerDetailDTO == null) {
                    PartnerDetailDTO partnerDetailDTO1 = new PartnerDetailDTO();
                    partnerDetailDTO1.setActiveNum(activeNum);
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutDate(time, 1);
                    partnerDetailDTO1.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO1);
                }
                if (partnerDetailDTO != null) {
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutDate(time, 1);
                    partnerDetailDTO.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO);
                }
            }
            Collections.reverse(list);
            return list;
        }
        if (merchantDTO.getSignAmount() == 2) {// 交易额按半年查
            // 先查出半年的时间
            for (int i = 0; i < 6; i++) {
                String time = com.cykj.pos.util.DateUtils.dateSubMonth(date, -i - 1);
                merchantDTO.setMonthType(time);
                PartnerDetailDTO partnerDetailDTO = posTransactionNoticeMapper.selectIncome(merchantDTO);
                if (partnerDetailDTO == null) {
                    PartnerDetailDTO partnerDetailDTO1 = new PartnerDetailDTO();
                    partnerDetailDTO1.setActiveNum(activeNum);
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutMonth(time, 2);
                    partnerDetailDTO1.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO1);
                }
                if (partnerDetailDTO != null) {
                    String cutOutTime = com.cykj.pos.util.DateUtils.cutOutMonth(time, 2);
                    partnerDetailDTO.setTime(cutOutTime);
                    list.add(i, partnerDetailDTO);
                }
            }
            Collections.reverse(list);
            return list;
        }
        return null;
    }

    @Override
    public AjaxResult jlVip(JSONObject jsonObject) {
        System.out.println("嘉联VIP通知"+JSONObject.toJSONString(jsonObject));
        BizJlMerchantInfoMemberVip bizJlMerchantInfoMemberVip = new BizJlMerchantInfoMemberVip();
        bizJlMerchantInfoMemberVip.setAgentId(jsonObject.getString("agentId"));
        bizJlMerchantInfoMemberVip.setMerchNo(jsonObject.getString("merchNo"));
        bizJlMerchantInfoMemberVip.setMerchName(jsonObject.getString("merchName"));
        bizJlMerchantInfoMemberVip.setCardNo(jsonObject.getString("cardNo"));
        bizJlMerchantInfoMemberVip.setPossn(jsonObject.getString("possn"));
        bizJlMerchantInfoMemberVip.setMemberType(jsonObject.getString("memberType"));
        bizJlMerchantInfoMemberVip.setOpMon(jsonObject.getString("opMon"));
        bizJlMerchantInfoMemberVip.setStartTime(jsonObject.getString("startTime"));
        bizJlMerchantInfoMemberVip.setEndTime(jsonObject.getString("endTime"));
        bizJlMerchantInfoMemberVip.setOrderId(jsonObject.getString("orderId"));
        bizJlMerchantInfoMemberVip.setAmount(jsonObject.getString("amount"));
        bizJlMerchantInfoMemberVip.setCreateTime(new Date());
        BizJlMerchantInfoMemberVip one = posTransactionNoticeMapper.getJlVip(bizJlMerchantInfoMemberVip);
        if (one == null){
            posTransactionNoticeMapper.save(bizJlMerchantInfoMemberVip);
        }else {
            System.out.println("已存在Vip****不分账*********"+JSONObject.toJSONString(jsonObject));
            return AjaxResult.error("已存在VIP");
        }
        if ("1".equals(jsonObject.getString("memberType"))){ // 收费项目

            LambdaQueryWrapper<AllocationRelation> lqw = Wrappers.lambdaQuery();
            lqw.eq(AllocationRelation::getPosSn, jsonObject.getString("possn"));
            // 查询出结算费率和关系倒叙
            List<AllocationRelation> list = iAllocationRelationService.list(lqw.orderByDesc(AllocationRelation::getLevel));
            // 插入记录表
            BizFeesCharged bizFeesCharged = new BizFeesCharged();
            String uuid = IdWorker.getIdStr();
            list.stream().forEach(e -> {
                if (e.getVip().compareTo(new BigDecimal(0.00)) > 0 ) {
                    bizFeesCharged.setMamountId(IdWorker.getIdStr());
                    bizFeesCharged.setOrgnname(String.valueOf(e.getMerchId()));
                    bizFeesCharged.setMerchantNo(jsonObject.getString("merchNo"));
                    bizFeesCharged.setSn(e.getPosSn());
                    bizFeesCharged.setSimcardfee(e.getVip().toString());
                    bizFeesCharged.setMamountStarts("1");
                    bizFeesCharged.setAmtType("3");
                    bizFeesCharged.setUuid(uuid);
                    bizFeesCharged.setChannel("17");
                    bizFeesCharged.setRmbStatus("2");
                    bizFeesCharged.setHostDate(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",new Date()));
                    bizFeesChargedService.insertBizFeesCharged(bizFeesCharged);
                    // 钱包给钱
                    BizMerchant merchantByMerchId = bizMerchantService.getMerchantByMerchId(e.getMerchId());
                    LambdaQueryWrapper<BizWalletNew> lambdaQueryWrapper = Wrappers.lambdaQuery();
                    lambdaQueryWrapper.eq(BizWalletNew::getUserId, merchantByMerchId.getUserId());
                    lambdaQueryWrapper.eq(BizWalletNew::getChannelId, "17");
                    BizWalletNew walletNew = bizWalletNewService.getOne(lambdaQueryWrapper);
                    BigDecimal rewardAmount = walletNew.getRewardAmount(); // 结算金额
                    BigDecimal walletAmount = walletNew.getWalletAmount(); // 总金额
                    BigDecimal addReward = new BigDecimal(0.00);
                    BigDecimal add1Wallet = new BigDecimal(0.00);
                    addReward = rewardAmount.add(e.getVip());
                    add1Wallet = walletAmount.add(e.getVip());
                    walletNew.setRewardAmount(addReward);
                    walletNew.setWalletAmount(add1Wallet);
                    boolean b = bizWalletNewService.saveOrUpdate(walletNew);
                }
            });
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult jlUpdateFee(JSONObject param) {
        String s = HttpUtil.doPostxxl(PosPCommonParamConfig.getJlUpdateFee(), JSONObject.toJSONString(param));
        JSONObject jsonObject = JSONObject.parseObject(s);

        if ("00".equals(jsonObject.getString("ret_code"))){
            String deviceSn = param.getString("deviceSn");
            // 查询费率
            BizPosMachine bizPosMachine = bizPosMachineService.selectPosBySnCode(deviceSn);
            // 原费率
            String fee = bizPosMachine.getFee();
            System.out.println(deviceSn+"原费率**"+fee);
            BizMerchantFeeName bizMerchantFeeName = posTransactionNoticeMapper.selectFeeName(fee);
            String feeName = bizMerchantFeeName.getFeeName();
            // 修改费率
            String feeId = param.getString("feeId");
            System.out.println(deviceSn+"修改费率**"+feeId);
            BizMerchantFeeName upFee = posTransactionNoticeMapper.selectFeeName(feeId);
            String upFeeFeeName = upFee.getFeeName();
            if (new BigDecimal(upFeeFeeName).compareTo(new BigDecimal(feeName)) > 0){
                BizMerchant bizMerchant = bizMerchantService.selectBizMerchantBySN(deviceSn);
                // 直属代理扣款钱包 1元   加入扣款记录
                AizDeductionWallet aizDeductionWallet =  posTransactionNoticeMapper.selectDeductionWallet(bizMerchant.getUserId());
                BigDecimal amount = aizDeductionWallet.getAmount();
                amount = amount.add(new BigDecimal("1"));
                aizDeductionWallet.setAmount(amount);
                posTransactionNoticeMapper.updateDeductionWallet(aizDeductionWallet);
                // 插入扣款记录
                AizDeductionRecords aizDeductionRecords = new AizDeductionRecords();
                aizDeductionRecords.setDeductionSn(deviceSn);
                aizDeductionRecords.setDeductionMerchId(bizMerchant.getMerchId());
                aizDeductionRecords.setDeductionMerchName(bizMerchant.getMerchName());
                aizDeductionRecords.setDeductionType("3");
                aizDeductionRecords.setDeductionAmount(1L);
                aizDeductionRecords.setDeductionResult("嘉联修改商户费率扣直属代理1元");
                aizDeductionRecords.setDeductionTime(new Date());
                aizDeductionRecordsService.save(aizDeductionRecords);
            }
            bizPosMachineService.updateFee(deviceSn,feeId);
            return AjaxResult.success("费率修改成功");
        }else {
            return AjaxResult.error("费率修改失败"+jsonObject.getString("ret_msg"));
        }

    }

    public static void main(String[] args) {
//        // 获取当前日期
//        LocalDate today = LocalDate.now();

/*        // 获取当前日期前7天的日期
        LocalDate sevenDaysAgo = today.minusDays(7);
        // 使用stream生成前7天的每一天
        Stream<LocalDate> datesStream = Stream.iterate(sevenDaysAgo, date -> date.plusDays(1))
                .limit(7);
        // 打印每一天的日期
       // datesStream.forEach(date -> System.out.println(date));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        datesStream.forEach(date -> System.out.println(date.format(formatter)));*/

 /*       for (int i = 1; i <= 6; i++) {
            DateTimeFormatter aaa = DateTimeFormatter.ofPattern("yyyy-MM");
            LocalDate date = today.minusMonths(i);
            System.out.println(date.format(aaa));
            System.out.println(date.getMonthValue()); // 输出月份数字
        }*/

     /*   List<TradingRankingDTO>  tradingRankingList = new ArrayList<>();
        tradingRankingList.add(new TradingRankingDTO("ss",45456.00));
        tradingRankingList.add(new TradingRankingDTO("ff",5454.00));
        tradingRankingList.add(new TradingRankingDTO("gg",9887.00));
        tradingRankingList.add(new TradingRankingDTO("ww",54.46));
        IntStream.range(0, tradingRankingList.size()).forEach(e->{
            tradingRankingList.get(e).setRank(e+1);
        });
        System.out.println(tradingRankingList);
*/

//        BigDecimal bigDecimal = new BigDecimal(0.6).subtract(new BigDecimal(0.52)).setScale(2,BigDecimal.ROUND_DOWN);
//        System.out.println(bigDecimal);
        System.out.println(new BigDecimal(3000).compareTo(new BigDecimal(3000)) );
    }

    /**
     * 押金返现打钱
     *
     * @param list
     * @param type 1 押金  0流量费
     * @param sy
     */
    private void cashback(List<AllocationRelation> list, SynchronizationDataDTO sy, String type, String isTwo) {
        list.stream().forEach(e -> {
            if (e.getServiceFee().compareTo(new BigDecimal(0.00)) > 0 || e.getSimFee().compareTo(new BigDecimal(0.00)) > 0) {
                BizMerchant merchantByMerchId = bizMerchantService.getMerchantByMerchId(e.getMerchId());
                LambdaQueryWrapper<BizWalletNew> lambdaQueryWrapper = Wrappers.lambdaQuery();
                lambdaQueryWrapper.eq(BizWalletNew::getUserId, merchantByMerchId.getUserId());
                lambdaQueryWrapper.eq(BizWalletNew::getChannelId, sy.getChannel());
                BizWalletNew walletNew = bizWalletNewService.getOne(lambdaQueryWrapper);
                BigDecimal rewardAmount = walletNew.getRewardAmount(); // 结算金额
                BigDecimal walletAmount = walletNew.getWalletAmount(); // 总金额
                BigDecimal addReward = new BigDecimal(0.00);
                BigDecimal add1Wallet = new BigDecimal(0.00);
                if ("1".equals(type)) { // 押金
                    addReward = rewardAmount.add(e.getServiceFee());
                    add1Wallet = walletAmount.add(e.getServiceFee());
                } else if ("0".equals(type)) { // 流量
                    if ("0".equals(isTwo)) { // 首次
                        addReward = rewardAmount.add(e.getSimFee());
                        add1Wallet = walletAmount.add(e.getSimFee());
                    } else if ("1".equals(isTwo)) { // 非首次
                        addReward = rewardAmount.add(e.getSimFeeLast());
                        add1Wallet = walletAmount.add(e.getSimFeeLast());
                    }
                }
                walletNew.setRewardAmount(addReward);
                walletNew.setWalletAmount(add1Wallet);
                boolean b = bizWalletNewService.saveOrUpdate(walletNew);
            }

        });

    }

    /**
     * 插入返现记录
     *
     * @param list  划拨关系记录
     * @param sy    交易数据层  isTwo
     * @param isTwo 0 流量首次  1 非首次
     */
    private void feeCharged(List<AllocationRelation> list, SynchronizationDataDTO sy, String amtType, String isTwo) {
        BizFeesCharged bizFeesCharged = new BizFeesCharged();
        list.stream().forEach(e -> {
            if (e.getServiceFee().compareTo(new BigDecimal(0.00)) > 0 || e.getSimFee().compareTo(new BigDecimal(0.00)) > 0) {
                bizFeesCharged.setMamountId(IdWorker.getIdStr());
                bizFeesCharged.setOrgnname(String.valueOf(e.getMerchId()));
                bizFeesCharged.setMerchantNo(sy.getMerchant_no());
                bizFeesCharged.setSn(e.getPosSn());
                if ("0".equals(amtType)) { // 流量
                    if ("0".equals(isTwo)) { // 首次
                        bizFeesCharged.setSimcardfee(e.getSimFee().toString());
                    } else if ("1".equals(isTwo)) { // 非首次
                        bizFeesCharged.setSimcardfee(e.getSimFeeLast().toString());
                    }
                } else if ("1".equals(amtType)) {
                    bizFeesCharged.setSimcardfee(e.getServiceFee().toString());
                }
                bizFeesCharged.setMamountStarts("1");
                bizFeesCharged.setAmtType(amtType);
                bizFeesCharged.setUuid(sy.getUuid());
                bizFeesCharged.setChannel(sy.getChannel());
                bizFeesCharged.setRmbStatus("2");
                bizFeesCharged.setHostDate(sy.getHost_date());
                bizFeesCharged.setCreateTime(DateUtil.getBaiDuTime());
                bizFeesChargedService.insertBizFeesCharged(bizFeesCharged);
            }
        });
    }

    /**
     * 判断交易是否存在
     *
     * @param sy
     */
    private boolean judge(SynchronizationDataDTO sy) {
        Map<String, String> map = new HashMap<>();
        Integer transaction = bizMerchTransactionsService.findTransaction(sy.getPos_sn(), String.valueOf(sy.getAmnount()), String.valueOf(sy.getHost_date()), String.valueOf(sy.getTrans_type()));
        if (transaction > 0) {
            map.put("ret_code", "0");
            map.put("ret_msg", "已有该笔交易");
            System.out.println("----交易已存在------");
            System.out.println("----------");
            return false;
        }
        return true;
    }

    /**
     * 算账
     *
     * @param list 代理结算信息
     * @param sy   交易数据
     * @return map
     */
    private Map<String, String> settleAccounts(List<AllocationRelation> list, SynchronizationDataDTO sy) {
        // 下级交易额*下级费率值 存起来算上级用
        //  上级代理分润 = 存起来的值 - 上级代理费率 * 交易额   依此类推
        //  把分润存到一张表里
        //  钱包给钱
        //  代理表数据统计要加钱
        // 有加3情况   判断是否存在 ‘ + ’ 真实手续费 = 手续费 - 3
        // 重复没有D0情况 基础上  加上代理设置的 D0值
        Map<String, String> map = new HashMap<>();
        // 查询设备
        BizPosMachine bizPosMachine = bizPosMachineService.selectPosBySnCode(sy.getPos_sn());
        if (bizPosMachine == null) {
            map.put("ret_code", "0");
            map.put("ret_msg", "设备不存在");
            System.out.println("----------------------------------");
            System.out.println("-----------设备不存在不分账-----------------------" + sy.getPos_sn());
            System.out.println("----------------------------------");
            return map;
        }
        // 获取厂商
        StorageEquipment manufacturerByid = bizPosMachineService.getManufacturerByid(bizPosMachine.getManufacturersId());
        // 创建一个list 存储代理分润金额   1代理编号  2交易额  3手续费  4分润金额 5 pos费率 6 代理费率
        List<AizProfitSharingRecord> sharingRecordList = new ArrayList<>();
        BigDecimal child = new BigDecimal("0.00");
        if (sy.getFee_name().contains("+")) {  // 判断是否加3
            String[] split = sy.getFee_name().split("\\+");
            String D0 = split[1]; // 加 n 手续费
            String addiAmount = new BigDecimal(sy.getAddi_amount().toString()).subtract(new BigDecimal(D0)).toString(); // 扣除D0
            sy.setAddi_amount(Double.parseDouble(addiAmount));
        }
        // 费率
        BigDecimal divide = new BigDecimal(sy.getAddi_amount().toString()).divide(new BigDecimal(sy.getAmnount().toString()), 5, RoundingMode.HALF_UP);
        // 判断是否需要调价分成  pos费率大于 0.6 部分属于调价
        BigDecimal bigDecimal = new BigDecimal(0.006);
        BigDecimal exceed = new BigDecimal(0);
        // 星驿付不参加分成
        if (divide.compareTo(bigDecimal) > 0 && !"16".equals(sy.getChannel())) {
            Double addi_amount = sy.getAddi_amount();  // 原手续费
            // 手续费需要按照 0.6算   超出0.6 部分按照比例计算
            String multiply = new BigDecimal(sy.getAmnount().toString()).multiply(new BigDecimal("0.006")).setScale(2, RoundingMode.DOWN).toString();
            sy.setAddi_amount(Double.parseDouble(multiply));
            // 需要去分成的钱
            exceed = new BigDecimal(addi_amount.toString()).subtract(new BigDecimal(multiply));
        }
        for (int i = 0; i < list.size(); i++) {
            BigDecimal fenCheng = new BigDecimal("0");
            BigDecimal fenRun = new BigDecimal("0.00");
            BigDecimal koukuan = new BigDecimal("0.00");
            BigDecimal gengXinKouKuan = new BigDecimal("0.00");
            BigDecimal d0Fee = new BigDecimal("0");
            AizProfitSharingRecord aizProfitSharingRecord = new AizProfitSharingRecord();
            // 代理结算信息
            AllocationRelation allocationRelation = list.get(i);
            Long merchId = allocationRelation.getMerchId();
            BizMerchant merchantByMerchId = bizMerchantService.getMerchantByMerchId(merchId);
            BigDecimal rate = new BigDecimal("0"); // 代理结算费率
            if (new BigDecimal(sy.getAddi_amount().toString()).divide(new BigDecimal(sy.getAmnount().toString()), 5, RoundingMode.DOWN).compareTo(new BigDecimal(0.0041)) == 1) { // 判断刷卡扫码
                rate = allocationRelation.getSettlementRate();// 代理费率刷卡、
                BigDecimal commission = new BigDecimal(allocationRelation.getCommission()).divide(new BigDecimal("100"));
                fenCheng = exceed.multiply(commission).setScale(2, RoundingMode.DOWN);
            } else {
                rate = allocationRelation.getQrCodeRate();// 代理费率扫码
            }
            if (sy.getFee_name().contains("+")) {
                d0Fee = allocationRelation.getD0Fee(); // D0 附加费 todo 辉哥说 扫码刷卡都给
            }
            // 先算最底层
            if (i == 0) {
                child = rate.multiply(new BigDecimal(sy.getAmnount().toString()));  // 交易额*下级费率值
                // 最低级的代理分润=手续费-代理费率*交易额  保留俩位小数 只舍不入 这个要存到起来给钱
                fenRun = new BigDecimal(sy.getAddi_amount().toString()).subtract(child).setScale(2, RoundingMode.DOWN);
                fenRun = fenRun.add(d0Fee);
                fenRun = fenRun.add(fenCheng);
                //将需要的信息存起来
            } else { // 除底层的上级
                BigDecimal multiply = rate.multiply(new BigDecimal(sy.getAmnount().toString()));// 交易额*费率值
                //  上级代理分润 = 存起来的值 - 上级代理费率 * 交易额   依此类推
                fenRun = child.subtract(multiply).setScale(2, RoundingMode.DOWN);
                fenRun = fenRun.add(d0Fee); // +3
                fenRun = fenRun.add(fenCheng); // + 调价
                // 赋值
                child = multiply;
            }
            // 查询扣款钱包
            AizDeductionWallet aizDeductionWallet =  posTransactionNoticeMapper.selectDeductionWallet(merchantByMerchId.getUserId());
            if (aizDeductionWallet != null){
                     // 需要扣款
                if (aizDeductionWallet.getAmount().compareTo(new BigDecimal("0.00")) > 0){
                    // 判断扣款金额和分润大小
                    if (fenRun.compareTo(aizDeductionWallet.getAmount()) > 0){ // 分润大于扣款
                        fenRun = fenRun.subtract(aizDeductionWallet.getAmount()).setScale(2, RoundingMode.DOWN);
                        koukuan = aizDeductionWallet.getAmount();
                        gengXinKouKuan = new BigDecimal(0.00); // 扣款金额变成了
                    }else { // 分润小于扣款 或等于
                        koukuan = fenRun;
                        gengXinKouKuan = aizDeductionWallet.getAmount().subtract(fenRun).setScale(2, RoundingMode.DOWN);
                        fenRun = fenRun.subtract(fenRun); // 分润为0
                    }
                    // 更新扣款钱包
                    aizDeductionWallet.setAmount(gengXinKouKuan);
                    int j = posTransactionNoticeMapper.updateDeductionWallet(aizDeductionWallet);
                }
            }
            //把数据存起来
            aizProfitSharingRecord.setMerchId(merchId);
            aizProfitSharingRecord.setMerchName(merchantByMerchId.getMerchName());
            aizProfitSharingRecord.setUserId(merchantByMerchId.getUserId());
            aizProfitSharingRecord.setAmnount(new BigDecimal(sy.getAmnount()));
            aizProfitSharingRecord.setFeeName(sy.getFee_name());
            aizProfitSharingRecord.setPosSn(sy.getPos_sn());
            aizProfitSharingRecord.setMerchantNo(sy.getMerchant_no());
            aizProfitSharingRecord.setShareAmount(fenRun);
            aizProfitSharingRecord.setDeductionAmount(koukuan);
            aizProfitSharingRecord.setSettlementRate(rate);
            aizProfitSharingRecord.setCreateTime(DateUtil.getBaiDuTime());
            aizProfitSharingRecord.setHostDate(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", sy.getHost_date()));
            aizProfitSharingRecord.setChannel(sy.getChannel());
            aizProfitSharingRecord.setManufacturerId(bizPosMachine.getManufacturersId());
            aizProfitSharingRecord.setManufacturerName(manufacturerByid.getManufacturerName());
            aizProfitSharingRecord.setModelId(bizPosMachine.getModelId());
            aizProfitSharingRecord.setModelName(bizPosMachine.getDeviceType());
            aizProfitSharingRecord.setUuid(Long.parseLong(sy.getUuid()));
            // 存起来
            sharingRecordList.add(aizProfitSharingRecord);
        }
        //  激活设备 有交易就激活
        LambdaQueryWrapper<BizPosMachineStatusRecords> le = Wrappers.lambdaQuery();
        le.eq(BizPosMachineStatusRecords::getSnCode, sy.getPos_sn());
        BizPosMachineStatusRecords record = bizPosMachineStatusRecordsService.getOne(le);
        if (record != null) {
            if (!"2".equals(record.getRecordsType())) { // w未激活
                PosMerchantRelatedDTO posMerchantRelatedDTO = new PosMerchantRelatedDTO();
                posMerchantRelatedDTO.setMerchId(bizPosMachine.getMerchId()); // 直属代理merchId
                posMerchantRelatedDTO.setPosCode(sy.getPos_sn());
                // 更新下激活时间
                BizPosMachineStatusRecords bizPosMachineStatusRecords = new BizPosMachineStatusRecords();
                bizPosMachineStatusRecords.setSnCode(sy.getPos_sn());
                bizPosMachineStatusRecords.setRecordsType("2");
                bizPosMachineStatusRecords.setActiveTime(com.cykj.pos.util.DateUtils.dateFormatString(DateUtil.getBaiDuTime()));
                bizPosMachineStatusRecordsService.updateMachineStatusRecordsByXXL(bizPosMachineStatusRecords);
                int pos = bizPosMachineMapper.updatePosOneRecords(sy.getPos_sn());
                machineStatusRecordsMapper.generatePosMerchantRelatedProcedure(posMerchantRelatedDTO);// 运行下函数
            }
        }
        // todo 1 钱包加钱 2 生成分润明细 3 代理累计交易额
        return payWalletMerchant(sharingRecordList, sy);
    }

    /**
     * 1 钱包加钱 2 生成分润明细 3 代理累计交易额
     *
     * @param sharingRecordList 分润明细
     * @param sy                交易数据
     * @return
     */
    private Map<String, String> payWalletMerchant(List<AizProfitSharingRecord> sharingRecordList, SynchronizationDataDTO sy) {
        Map<String, String> map = new HashMap<>();
        map.put("ret_code", "0");
        map.put("ret_msg", "交易成功");
        Double amnount = sy.getAmnount();
        try {
            sharingRecordList.stream().forEach(e -> {
                boolean save = iAizProfitSharingRecordService.save(e);
                // 代理累计金额
                SysUser sysUser = sysUserService.selectUserByUserId(e.getUserId());
                Double total_trans_amount = sysUser.getTotalTransAmount(); // 总交易量
                sysUser.setTotalTransAmount(Double.parseDouble(new BigDecimal(total_trans_amount.toString()).add(new BigDecimal(amnount.toString())).toString()));
                Double year_trans_amount = sysUser.getYearTransAmount(); // 年交易量
                Double this_month_trans_amount = sysUser.getThisMonthTransAmount(); // 当月交易量
                Double todayTransAmount = sysUser.getTodayTransAmount(); // 当日交易量
                // 全渠道
                sysUser.setYearTransAmount(Double.parseDouble(new BigDecimal(year_trans_amount.toString()).add(new BigDecimal(amnount.toString())).toString()));
                sysUser.setThisMonthTransAmount(Double.parseDouble(new BigDecimal(this_month_trans_amount.toString()).add(new BigDecimal(amnount.toString())).toString()));
                sysUser.setTodayTransAmount(Double.parseDouble(new BigDecimal(todayTransAmount.toString()).add(new BigDecimal(amnount.toString())).toString()));
                // 分支渠道
                Integer channel = Integer.parseInt(sy.getChannel());
                // 查询分支统计
                LambdaQueryWrapper<AizStatisticalMerchant> lLambdaQueryWrapper =   Wrappers.lambdaQuery();
                lLambdaQueryWrapper.eq(AizStatisticalMerchant::getChannelId,channel);
                lLambdaQueryWrapper.eq(AizStatisticalMerchant::getUserId,e.getUserId());
                AizStatisticalMerchant one = iAizStatisticalMerchantService.getOne(lLambdaQueryWrapper);
                Double channeltotal_trans_amount = one.getTotalTransAmount(); // 总交易量
                Double channelyear_trans_amount = one.getYearTransAmount(); // 年交易量
                Double channelthis_month_trans_amount = one.getThisMonthTransAmount(); // 当月交易量
                Double channeltodayTransAmount = one.getTodayTransAmount(); // 当日交易量
                one.setTotalTransAmount(Double.parseDouble(new BigDecimal(channeltotal_trans_amount.toString()).add(new BigDecimal(amnount.toString())).toString()));
                one.setYearTransAmount(Double.parseDouble(new BigDecimal(channelyear_trans_amount.toString()).add(new BigDecimal(amnount.toString())).toString()));
                one.setThisMonthTransAmount(Double.parseDouble(new BigDecimal(channelthis_month_trans_amount.toString()).add(new BigDecimal(amnount.toString())).toString()));
                one.setTodayTransAmount(Double.parseDouble(new BigDecimal(channeltodayTransAmount.toString()).add(new BigDecimal(amnount.toString())).toString()));
                if (e.getShareAmount().compareTo(new BigDecimal("0.00")) > 0) {
                    // 查询钱包   1 钱包加钱
                    LambdaQueryWrapper<BizWalletNew> lqw = Wrappers.lambdaQuery();
                    lqw.eq(BizWalletNew::getUserId, e.getUserId());
                    lqw.eq(BizWalletNew::getChannelId, e.getChannel());
                    BizWalletNew walletNew = bizWalletNewService.getOne(lqw);
                    BigDecimal profitAmount = walletNew.getProfitAmount(); // 结算金额
                    BigDecimal walletAmount = walletNew.getWalletAmount(); // 总金额
                    BigDecimal addProfit = profitAmount.add(e.getShareAmount());
                    BigDecimal add1Wallet = walletAmount.add(e.getShareAmount());
                    walletNew.setProfitAmount(addProfit);
                    walletNew.setWalletAmount(add1Wallet);
                    boolean b = bizWalletNewService.saveOrUpdate(walletNew);
                    // 生成分润明细
                   // boolean save = iAizProfitSharingRecordService.save(e);
                    Double totalProfitAmount = sysUser.getTotalProfitAmount(); // 分润合计
                    Double yearProfitAmount = sysUser.getYearProfitAmount(); // 年分润合计
                    Double thisMonthProfitAmount = sysUser.getThisMonthProfitAmount(); // 本月分润合计
                    Double todayProfitAmount = sysUser.getTodayProfitAmount(); // 日分润合计
                    sysUser.setTotalProfitAmount(Double.parseDouble(new BigDecimal(totalProfitAmount.toString()).add(e.getShareAmount()).toString()));
                    sysUser.setYearProfitAmount(Double.parseDouble(new BigDecimal(yearProfitAmount.toString()).add(e.getShareAmount()).toString()));
                    sysUser.setThisMonthProfitAmount(Double.parseDouble(new BigDecimal(thisMonthProfitAmount.toString()).add(e.getShareAmount()).toString()));
                    sysUser.setTodayProfitAmount(Double.parseDouble(new BigDecimal(todayProfitAmount.toString()).add(e.getShareAmount()).toString()));

                    Double channeltotalProfitAmount = one.getTotalProfitAmount(); // 分润合计
                    Double channelyearProfitAmount = one.getYearProfitAmount(); // 年分润合计
                    Double channelthisMonthProfitAmount = one.getThisMonthProfitAmount(); // 本月分润合计
                    Double channeltodayProfitAmount = one.getTodayProfitAmount(); // 日分润合计
                    one.setTotalProfitAmount(Double.parseDouble(new BigDecimal(channeltotalProfitAmount.toString()).add(e.getShareAmount()).toString()));
                    one.setYearProfitAmount(Double.parseDouble(new BigDecimal(channelyearProfitAmount.toString()).add(e.getShareAmount()).toString()));
                    one.setThisMonthProfitAmount(Double.parseDouble(new BigDecimal(channelthisMonthProfitAmount.toString()).add(e.getShareAmount()).toString()));
                    one.setTodayProfitAmount(Double.parseDouble(new BigDecimal(channeltodayProfitAmount.toString()).add(e.getShareAmount()).toString()));
                }
                // 更新全渠道统计
                int i = sysUserService.updateUserTransAndProfit(sysUser);
                // 更新渠道分支统计
                boolean b = iAizStatisticalMerchantService.saveOrUpdate(one);
            });
        } catch (Exception e) {
            System.out.println("----------------------------------");
            System.out.println("----钱包打钱--生成分润记录----累计交易出现异常----");
            System.out.println("----------------------------------");
            e.printStackTrace();
            map.put("ret_code", "0");
            map.put("ret_msg", "交易异常");
            return map;
        }
        return map;
    }


}
